﻿using LD.Host;
using System;
using System.Threading;

namespace LD.Common
{
    public class MutexEx
    {
        private object locker = new object();
        private bool isLock = false;
        private object obj = new object();
        private int taskId = 0;
        public void Enter()
        {
            try
            {
                lock (obj)
                {
                    if (isLock && taskId == Thread.CurrentThread.ManagedThreadId)
                    {
                        Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ":已加锁");
                        return;
                    }
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ":请求加锁");
                    Monitor.Enter(locker);
                    isLock = true;
                    taskId = Thread.CurrentThread.ManagedThreadId;
                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ":加锁");
                }
            }
            catch (Exception ex)
            {
                Log4.Error(ex);
            }
        }
        public void Exit()
        {
            if (isLock && taskId == Thread.CurrentThread.ManagedThreadId)
            {
                Monitor.Exit(locker);
                isLock = false;
                Console.WriteLine(Thread.CurrentThread.ManagedThreadId + ":解锁");
            }
        }
        public bool Locker()
        {
            lock (obj)
            {
                if (isLock)
                    return true;
                else
                {
                    isLock = true;
                    return false;
                }
            }
        }
        public void UnLocker()
        {
            lock (obj)
            {
                isLock = false;
            }
        }
    }
}
